from sqlalchemy.orm import scoped_session
from .db import SessionFactory
from conf import conf
from .my_redis import MyRedis
from .mongo_api import MongoManager
from .utils import Utils
from .my_rabbitmq import RabbitmqApi
import asyncio

class G(object):
    _instance = None

    @classmethod
    def getInstance(cls):
        if cls._instance is None:
            cls._instance = cls()
        return cls._instance

    def __init__(self):
        self.conf = conf
        self.utils = Utils
        self._session = None

    @property
    def current_ioloop_instance(self):
        return asyncio.get_event_loop()

    @property
    def session(self):
        if self._session is None:
            self._session = scoped_session(SessionFactory)
        return self._session

    @property
    def redis(self):
        return MyRedis.getInstance(host=conf.redis.host,
                                   port=conf.redis.port, password=conf.redis.password,
                                   decode_responses=False)

    @property
    def mongo(self):
        return MongoManager(conf.mongo)

    '''
    @property
    def rabbitmq(self):
        """ 自定义rabbitmq """
        return RabbitmqApi.getInstance(conf.rabbitmq.dsn)
    '''

    def clear(self):
        """ 释放资源 """
        if self._session is not None:
            self._session.remove()
        self._session = None

        #del self.rabbitmq.channel

